package cn.golxen.rsms.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

@Slf4j
public class WxGetOpenIdUtils {
    public static String getOpenId(String code){
        try {
//            log.info("code" + code);
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            url += "?appid=wx60d7691f0bf92f27";//自己的appid
            url += "&secret=cc05377701a77e11a99d5db064faa5e4";//自己的appSecret
            url += "&js_code=" + code;
            url += "&grant_type=authorization_code";
            url += "&connect_redirect=1";
            String res = null;
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            // DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);    //GET方式
            CloseableHttpResponse response = null;
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()          // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)             // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(false).build();           // 将上面的配置信息 运用到这个Get请求里
            httpget.setConfig(requestConfig);                         // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpget);                   // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            log.info("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                res = EntityUtils.toString(responseEntity);
                log.info("响应内容长度为:" + responseEntity.getContentLength());
                log.info("响应内容为:" + res);
            }
            // 释放资源
            httpClient.close();
            response.close();
            JSONObject jo = JSON.parseObject(res);
            String openid = jo.getString("openid");
//            log.info("openid" + openid);
            return openid;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
